﻿@model UploadFileMVCWebApplication.Models.UploadViewModel

@{
    ViewData["Title"] = "主页";
}

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow-lg">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">文件上传</h4>
                </div>
                <div class="card-body">
                    <form id="uploadForm" method="post" enctype="multipart/form-data" class="mb-4">
                        <div class="input-group">
                            <input type="file" id="fileInput" name="file" class="form-control" multiple>
                            <button type="submit" class="btn btn-primary">
                                <i class="fa fa-upload mr-1"></i> 上传
                            </button>
                        </div>
                        <div class="mt-2 text-muted small">
                            支持格式：jpg、png、pdf、doc、docx、xls、xlsx、txt
                        </div>
                    </form>

                    <div id="uploadStatus" class="mt-3 mb-3"></div>

                    <div id="uploadResults">
                        <h5>上传历史</h5>
                        <div id="fileList" class="list-group">
                            <div class="text-center text-muted py-3">暂无上传文件</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.getElementById('uploadForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const fileInput = document.getElementById('fileInput');
        const files = fileInput.files;

        if (files.length === 0) {
            showMessage('请选择文件', 'danger');
            return;
        }


        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append('files', files[i]);
        }

        uploadFiles(formData);
    });

       async function uploadFiles(formData) {
        try {
            // 显示上传中状态
            document.getElementById('uploadStatus').innerHTML =
                '<div class="alert alert-info"><i class="fa fa-spinner fa-spin mr-2"></i>正在上传文件...</div>';
                 // 使用唯一键名添加文件（或者使用数组语法）
       
                 console.log(formData.length)
            const response = await fetch('/FileUpload/Upload', {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                const data = await response.json();
                 console.log('响应数据:', data); // 打印响应数据
                // 清空上传状态
                document.getElementById('uploadStatus').innerHTML = '';

                // 智能解析响应格式
                if (Array.isArray(data)) {
                    // 处理文件数组
                    if (data.length > 0) {
                        const fileList = document.getElementById('fileList');

        // 如果是首次上传，清空"暂无上传文件"提示
        if (fileList.querySelector('.text-muted')) {
            fileList.innerHTML = '';
        }
                        console.log('后端返回的文件总数:', data.length); // 关键：确认这里是否为3
                       data.forEach((file, index) => {
                            console.log(`遍历第${index+1}个文件:`, file.OriginalName); // 确认打印3个文件名
                            addFileToList(file);
            });
                        showMessage(`成功上传 ${data.length} 个文件`, 'success');
                    } else {
                        showMessage('未上传任何文件', 'warning');
                    }
                } else if (typeof data === 'object' && data !== null) {
                    // 处理单个文件对象
                    // 检查必要的属性
                    if (typeof data.OriginalName === 'string' && data.OriginalName.trim() !== '' &&
                typeof data.DownloadUrl === 'string' && data.DownloadUrl.trim() !== '' ) {
                        addFileToList(data);
                        showMessage(`"${data.OriginalName}" 上传成功`, 'success');
                    } 
                
                   else {
                        showMessage('上传失败：响应格式不完整', 'danger');
                   }
                } 
                else {
                    showMessage('上传失败：未知响应格式', 'danger');
                }
            } else {
                const error = await response.text();
                showMessage(`上传失败: ${error}`, 'danger');
            }
        } catch (error) {
            showMessage(`上传出错: ${error.message}`, 'danger');
        }
    }

    function addFileToList(fileData) {
        // const fileList = document.getElementById('fileList');

        // // 如果是首次上传，清空"暂无上传文件"提示
        // if (fileList.querySelector('.text-muted')) {
        //     fileList.innerHTML = '';
        // }
        console.log('显示文件列表的长度',fileList.length);
        const fileItem = document.createElement('div');
        fileItem.className = 'list-group-item list-group-item-action flex-column align-items-start';
        fileItem.innerHTML = `
            <div class="d-flex w-100 justify-content-between">
                <h5 class="mb-1">${escapeHtml(fileData.OriginalName)}</h5>
                <small>${fileData.Size}</small>
            </div>
            <p class="mb-1 text-muted">上传时间: ${formatDateTime(fileData.UploadedAt)}</p>
            <div class="mt-2">
                <a href="${fileData.DownloadUrl}" class="btn btn-sm btn-primary" download>
                    <i class="fa fa-download mr-1"></i> 下载
                </a>
            </div>
        `;

        fileList.prepend(fileItem);
    }

    function showMessage(message, type) {
        const statusDiv = document.getElementById('uploadStatus');
        statusDiv.className = `alert alert-${type} mt-3 mb-3`;
        statusDiv.textContent = message;

        // 3秒后自动隐藏
        setTimeout(() => {
            statusDiv.classList.add('fade');
            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 300);
        }, 3000);
    }

    // 辅助函数
    function escapeHtml(text) {
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function formatDateTime(dateTime) {
        const date = new Date(dateTime);
        return date.toLocaleString();
    }
</script>